package com.crack.nga2.custom;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

/**
 * 垂直线性扫描图
 * Created by Administrator on 2016/1/22.
 */
public class VerticalScanView extends View {

    public VerticalScanView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private Paint mLinePaint;

    private void init() {
        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mLinePaint.setColor(Color.BLACK);
        mLinePaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int width;
        int height;
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {
            width = 100;
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else {
            height = 100;
        }
        setMeasuredDimension(width, height);
        mRect = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());
        Shader.TileMode tile = Shader.TileMode.REPEAT;
        LinearGradient gradient = new LinearGradient(0, height, 0, 0, new int[]{Color.argb(0, 0, 0, 0), Color.DKGRAY}, null, tile);
        mLinePaint.setShader(gradient);
    }

    private int mY;
    private RectF mRect;

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(0, getMeasuredHeight() - mY);
        canvas.drawRect(mRect, mLinePaint);
        canvas.restore();
    }

    public void onStart() {
        flag = true;
        mHandler.post(runnable);
    }

    /**
     * 立刻终止
     */
    public void onStop() {
        flag = false;
    }

    boolean flag = false;

    boolean flag1 = false;

    /**
     * 扫描完后终止
     */
    public void onStopComplete(){flag1 = true;}

    Handler mHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mY += getMeasuredHeight()/10;
            if (mY >= getMeasuredHeight() * 2){
                mY = 0;
                if(flag1){
                    flag1 = false;
                    return;
                }
            }
            invalidate();
            if (flag) {
                mHandler.postDelayed(this, 20);
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        onStop();
    }
}
